from rest_framework.views import APIView,Response
from goods.models import Site,Order,User
from utils.alipay import MyAliPay
from utils.jwt_tool import JwtTool
from django.db import transaction
from utils.redis_tool import RedisTool
import time


class Addorder(MyAliPay):
    def post(self,request):
        # 获取前端数据
        u_id = request.data.get('u_id')
        l_id = request.data.get('l_id')
        m_id = request.data.get('m_id')
        alipay_type = request.data.get('alipay_type')
        total_price = request.data.get('total_price')
        order_id = str(time.time()).replace(".", "")
        Order.objects.create(u_id=u_id,
                             l_id=l_id,
                             alipay_type=alipay_type,
                             order_number=order_id,
                             m_id=m_id)
        pay_url = self.get_trade_url(order_id, total_price)
        return Response({'msg':'创建订单成功', 'code':200, 'url':pay_url})


class DelOrder(APIView):
    def post(self,request):
        o_id = request.data.get('id')
        Order.objects.filter(id=o_id).delete()
        return Response({'msg':'删除订单成功', 'code':200})


class GetOrder(APIView):
    def get(self,request):
        order_info = Order.objects.all()
        list7 = []
        for i in order_info:
            dict7 = {
                'id':i.id,
                'u_id':i.u_id,
                'm_id':i.m_id,
                'l_id':i.l_id,
                'c_time':i.c_time,
                'alipay_type':i.alipay_type,
                'order_number':i.order_number
            }
            list7.append(dict7)
        return Response({'msg':'展示所有订单成功', 'code':200, 'data':list7})


class GetOneOrder(APIView):
    def get(self,request):
        o_id = request.data.get('id')
        order_info = Order.objects.filter(id=o_id).all()
        list8 = []
        for i in order_info:
            dict8 = {
                'id': i.id,
                'u_id': i.u_id,
                'm_id': i.m_id,
                'l_id': i.l_id,
                'c_time': i.c_time,
                'alipay_type': i.alipay_type,
                'order_number': i.order_number
            }
            list8.append(dict8)
        return Response({'msg':'展示单个订单成功', 'code':200, 'data':list8})